require 'uri'

class Api::V1::SpusController < Api::V1::BaseController
  skip_before_action :authenticate_request!
  before_action :authenticate_request

  def index
    @spus = Spu.where(state: :onsale, published: true)
    if params[:shop_category_id].presence
      @shop_category = ShopCategory.find_by_id params[:shop_category_id]
      if @shop_category.presence
        if @shop_category.level == 2
          @spus = @spus.joins(:shop_category).where("shop_categories.parent_id = ?", @shop_category.id)
        elsif @shop_category.level == 3
          @spus = @spus.where(shop_category_id: params[:shop_category_id])
        end
      end
    end
    if params[:brand_id].presence
      @spus = @spus.where(brand_id: params[:brand_id])
    end
    if params[:sales_price].presence
      @spus = @spus.joins(:skus).group(:spu_id).order("min(skus.sale_price) #{params[:sales_price]}")
    elsif params[:sales_volumn].presence
      @spus = @spus.order("sales_volume DESC")
    elsif params[:newest].presence
      @spus = @spus.order("created_at DESC")
    end
    if params[:handpick].presence
      @spus = @spus.where(handpick: ActiveModel::Type::Boolean.new.cast(params[:handpick]))
    end
    if params[:promotion].presence
      @spus = @spus.where(promotion: ActiveModel::Type::Boolean.new.cast(params[:promotion]))
    end
    if @current_area.presence
      @spus = spus_where_area(@spus, @current_area.id)
    end
    @spus = @spus.page(params[:page]).per(params[:per])
  end

  def show
    @is_favorited = false
    @spu = Spu.find params[:id]
    if params[:user_id].presence
      @user = User.find params[:user_id]
      @is_favorited = @spu.is_favorited?(@user.id)
    end
    @service_url = request.headers['Authorization'].blank? ? "" : URI.encode("http://www.hnxfsy.cn/mobile/chats?shop_name=#{@spu.shop.blank? ? "" : @spu.shop.name}&shop_id=#{@spu.shop_id}&token=#{request.headers['Authorization'].split(' ').last}")
  end
  
end
